package mybatis_test;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisTest {
	public static void main(String[] args) throws IOException 	{
		String resource = "mybatis_test/SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
//		int chr = -1;
//		while((chr = inputStream.read()) != -1)		{
//			System.out.print((char)chr);
//		}
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = sqlSessionFactory.openSession();
		
		try	{
			//--insert method
//			session.insert("mybatis_test.BlogMapper.insert", new BlogMapper(5, "yuanyuan"));
//			session.commit();
			
			//--select method
//			List<BlogMapper> list = session.selectList("mybatis_test.BlogMapper.getAll");
//			for(BlogMapper bm : list)	{
//				System.out.println(bm.getId() + " "+ bm.getName());
//			}
			
//			List<HashMap<String, Object>> list = session.selectList("mybatis_test.BlogMapper.getById", new Integer(1));
//			for(HashMap<String, Object> hashmap : list)	{
//				Set<Entry<String, Object>> entrySet = hashmap.entrySet();
//				for(Entry<String, Object> en : entrySet)	{
//					System.out.println(en.getKey() + " = " + en.getValue());
//				}
//			}
			
			//--select one method
//			HashMap<String, Object> hashmap = session.selectOne("mybatis_test.BlogMapper.getById", new Integer(1));
//			Set<Entry<String, Object>> entrySet = hashmap.entrySet();
//			for(Entry<String, Object> en : entrySet)		{
//				System.out.println(en.getKey() + " = "+en.getValue());
//			}
			
			//--complicated resultmap
//			UserInfoMap uim = session.selectOne("mybatis_test.BlogMapper.getDetailById", new Integer(1));
//			System.out.println(1);
			
//			--delete method
//			session.delete("mybatis_test.BlogMapper.deleteById", 5);
//			session.commit();
			
			//--select method by using ResultHandler to do more complex thing
//			myResultHandler resultHandler = new myResultHandler();
//			session.select("mybatis_test.BlogMapper.getAll", resultHandler);
//			for(BlogMapper bm : resultHandler.list)	{
//				System.out.println(bm.getId() + " "+ bm.getName());
//			}

		}finally	{
		session.close();
		}
	}
	
	static class myResultHandler implements ResultHandler		{
		List<BlogMapper> list = new ArrayList<>();
		
		@Override
		public void handleResult(ResultContext context) {
			// TODO Auto-generated method stub
			BlogMapper bm = (BlogMapper)context.getResultObject();
			bm.setName(bm.getName()+" interrupted");
			list.add(bm);
		}
		
	}
}


